package de.lot.action;

import de.lot.auth.PasswordBean;
import de.lot.auth.PasswordManager;
import de.lot.model.LotUser;
import de.lot.model.Role;
import javax.persistence.EntityManager;
import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.contexts.Context;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;

/**
 * RegisterAction enables the registration of new users to the systems. Enabled
 * for admins only.
 *
 * @author Stefan Kohler <kohler.stefan@gmail.com>
 */
@Name("registerAction")
public class RegisterAction {

    @Logger
    private Log log;
    @In
    FacesMessages facesMessages;

    /**
     * Registers a new user and adds one or more roles to his identity
     *
     * @return "success" if no exception occurs
     * @see Role
     * @see LotUser
     */
    public String register() {
        Context eventContext = Contexts.getEventContext();
        PasswordBean passwordBean = (PasswordBean) eventContext.get("passwordBean");
        if (!passwordBean.verify()) {
            facesMessages.addToControl("confirm", "Value does not match password");
            return null;
        }

        LotUser newUser = (LotUser) Contexts.lookupInStatefulContexts("newUser");
        PasswordManager passwordManager = (PasswordManager) Component.getInstance(PasswordManager.class);
        newUser.setPasswordHash(passwordManager.hash(passwordBean.getPassword()));

        //TODO: CHANGE ROLE-SETTING HERE: UI-DEPENDENCE.
        Role role = new Role();
        role.setName("admin");

        EntityManager entityManager = (EntityManager) Component.getInstance("entityManager");

        entityManager.persist(role);


        newUser.setRole(role);


        entityManager.persist(newUser);
        facesMessages.add("Successfully created new User: #{newUser.name}");


        return "success";
    }
}
